<template>
    <div class="company-desktop">
        <!-- 顶部卡片区域 -->
        <div class="top-cards">
            <!-- 综合概况卡片 -->
            <div class="overview-card">
                <div class="card-title">综合概况</div>
                <div class="overview-grid">
                    <div class="overview-item green">
                        <div class="number">562</div>
                        <div class="label">接入车辆</div>
                    </div>
                    <div class="overview-item red">
                        <div class="number">500</div>
                        <div class="label">在线车辆</div>
                    </div>
                    <div class="overview-item teal">
                        <div class="number">3</div>
                        <div class="label">开通线路</div>
                    </div>
                    <div class="overview-item blue">
                        <div class="number">16592</div>
                        <div class="label">累计行驶里程(km)</div>
                    </div>
                </div>
            </div>

            <!-- 企业信息卡片 -->
            <div class="company-card">
                <div class="card-title">企业信息</div>
                <div class="company-info">
                    <div class="info-item">
                        <span class="label">车企名称:</span>
                        <span class="value">上海仙途智能科技有限公司</span>
                    </div>
                    <div class="info-item">
                        <span class="label">营业执照:</span>
                        <span class="value status-uploaded">已上传</span>
                    </div>
                    <div class="info-item">
                        <span class="label">公司法人:</span>
                        <span class="value">*利</span>
                    </div>
                    <div class="info-item">
                        <span class="label">身份证照片:</span>
                        <span class="value status-uploaded">已上传</span>
                    </div>
                    <div class="info-item">
                        <span class="label">负责人姓名:</span>
                        <span class="value">周丽</span>
                    </div>
                    <div class="info-item">
                        <span class="label">负责人电话:</span>
                        <span class="value">16266659859</span>
                    </div>
                </div>
            </div>
        </div>

        <!-- 标签页区域 -->
        <div class="tab-content">
            <a-tabs v-model:activeKey="activeTab" class="main-tabs">
                <!-- 车辆列表标签页 -->
                <a-tab-pane key="vehicleList" tab="车辆列表">
                    <div class="vehicle-list-content">
                        <a-table 
                            :columns="vehicleColumns" 
                            :data-source="state.vehicleData" 
                            :pagination="vehiclePagination"
                            :row-key="record => record.id"
                            size="middle"
                        >
                            <template #bodyCell="{ column, record }">
                                <template v-if="column.key === 'action'">
                                    <a @click="viewVehicleDetail(record)" style="color: #1890ff;">查看详情</a>
                                </template>
                            </template>
                        </a-table>
                    </div>
                </a-tab-pane>

                <!-- 运营线路标签页 -->
                <a-tab-pane key="operationRoutes" tab="运营线路">
                    <div class="routes-content">
                        <a-table 
                            :columns="routeColumns" 
                            :data-source="state.routeData" 
                            :pagination="routePagination"
                            :row-key="record => record.id"
                            size="middle"
                        >
                            <template #bodyCell="{ column, record }">
                                <template v-if="column.key === 'action'">
                                    <a @click="viewRouteDetail(record)" style="color: #1890ff;">查看详情</a>
                                </template>
                            </template>
                        </a-table>
                    </div>
                </a-tab-pane>

                <!-- 运营区域标签页 -->
                <a-tab-pane key="operationAreas" tab="运营区域">
                    <div class="areas-content">
                        <div class="map-container">
                            <div id="operation-map" class="map-content"></div>
                        </div>
                    </div>
                </a-tab-pane>
            </a-tabs>
        </div>
    </div>
</template>

<script setup>
import { ref, reactive, onMounted, onUnmounted, watch } from 'vue'
import { message } from 'ant-design-vue'
import { backManufacturerDetail, backVehicleQueryPage
    , backLineQueryPage,backVehicleDetail,backVehicleOptCount,backFenceQueryPage } from '@/service/nmcApi'


const state = reactive({
    manufacturerId:"2", //车企id
    manufacturerDetail: {}, //车企详情
    vehicleData: [], //车辆数据
    routeData: [], //线路数据
    fenceData: [] //电子围栏数据
})



// 当前激活的标签页
const activeTab = ref('vehicleList')

// 车辆列表数据
const vehicleColumns = [
    {
        title: '车牌',
        dataIndex: 'plate_license',
        key: 'plate_license',
        width: 120
    },
    {
        title: '车型',
        dataIndex: 'carModel',
        key: 'carModel',
        width: 120
    },
    {
        title: '车架号',
        dataIndex: 'plate_vin',
        key: 'plate_vin',
        width: 180
    },
    {
        title: '运营生效时间',
        dataIndex: 'fprq',
        key: 'fprq',
        width: 140
    },
    {
        title: '运营截止时间',
        dataIndex: 'sxrq',
        key: 'sxrq',
        width: 140
    },
    {
        title: '接入状态',
        dataIndex: 'accessStatus',
        key: 'accessStatus',
        width: 100
    },
    {
        title: '运营公司',
        dataIndex: 'operator',
        key: 'operator',
        width: 100
    },
    {
        title: '操作',
        key: 'action',
        width: 100,
        fixed: 'right'
    }
]


const vehiclePagination = ref({
    current: 1,
    pageSize: 10,
    total: 1,
    showSizeChanger: true,
    showQuickJumper: true,
    showTotal: (total) => `${total}条`,
    onChange: (page, pageSize) => {
        vehiclePagination.value.current = page
        vehiclePagination.value.pageSize = pageSize
        // 这里可以调用API获取数据
    }
})

// 运营线路数据
const routeColumns = [
    {
        title: '线路名称',
        dataIndex: 'routeName',
        key: 'routeName',
        width: 150
    },
    {
        title: '线路编号',
        dataIndex: 'routeCode',
        key: 'routeCode',
        width: 120
    },
    {
        title: '起点',
        dataIndex: 'startPoint',
        key: 'startPoint',
        width: 150
    },
    {
        title: '终点',
        dataIndex: 'endPoint',
        key: 'endPoint',
        width: 150
    },
    {
        title: '线路长度(km)',
        dataIndex: 'length',
        key: 'length',
        width: 120
    },
    {
        title: '运营状态',
        dataIndex: 'status',
        key: 'status',
        width: 100
    },
    {
        title: '车辆数量',
        dataIndex: 'vehicleCount',
        key: 'vehicleCount',
        width: 100
    },
    {
        title: '操作',
        key: 'action',
        width: 100,
        fixed: 'right'
    }
]


const routePagination = ref({
    current: 1,
    pageSize: 10,
    total: 1,
    showSizeChanger: true,
    showQuickJumper: true,
    showTotal: (total) => `${total}条`,
    onChange: (page, pageSize) => {
        routePagination.value.current = page
        routePagination.value.pageSize = pageSize
        // 这里可以调用API获取数据
    }
})

// 地图相关变量
let mapInstance = null
let polygons = []

// 查看车辆详情
const viewVehicleDetail = (record) => {
    console.log('查看车辆详情:', record)
    message.info('车辆详情功能待实现')
}

// 查看线路详情
const viewRouteDetail = (record) => {
    console.log('查看线路详情:', record)
    message.info('线路详情功能待实现')
}

// 初始化地图
const initMap = () => {
    if (mapInstance) return
    
    mapInstance = new AMap.Map('operation-map', {
        mapStyle: 'amap://styles/whitesmoke',
        doubleClickZoom: false,
        zoom: 13,
        center: [114.325512, 30.367111],
        animateEnable: false
    })
    

    
    state.fenceData.forEach((area, index) => {
        if(area.bizFenceAreaList && area.bizFenceAreaList.length > 0){


        area.bizFenceAreaList.map(item => {
            let path = item.pointList.map(point => [point.lo, point.la])
            console.log(path, 'path---state.fenceData')
            
            const polygon = new AMap.Polygon({
                path: path,
                fillColor: '#1890ff',
                fillOpacity: 0.3,
                strokeWeight: 2,
                strokeColor: '#1890ff'
            })
            
            // 添加文本标签
            const text = new AMap.Text({
                text: area.name +'-'+item.name,
                position: calculateCenter(path),
                style: {
                    fontSize: '14px',
                    fontWeight: 'bold',
                    color: '#333',
                    backgroundColor: 'transparent',
                    // padding: '4px 8px',
                    // borderRadius: '4px',
                    border: 'unset'
                }
            })
            
            mapInstance.add(polygon)
            mapInstance.add(text)
            polygons.push(polygon)

            console.log(polygon,text, 'polygon')
        })

    }   
    })
    
    // 调整地图视野以显示所有多边形
    if (polygons.length > 0) {
        mapInstance.setFitView(polygons, false, [60, 60, 60, 60], 16)
    }
}
// 计算区域中心点
const calculateCenter = (path) => {
    let lngSum = 0
    let latSum = 0

    path.forEach(point => {
        lngSum += point[0]
        latSum += point[1]
    })
    return [lngSum / path.length,latSum / path.length]
}
onMounted(() => {
    // 监听标签页切换，当切换到运营区域时初始化地图
    const unwatch = watch(activeTab, (newTab) => {
        if (newTab === 'operationAreas') {
            setTimeout(() => {
                initMap()
            }, 100)
        }
    })
    

    // 获取车企详情 
    getManufacturerDetail()
    // 获取车辆分页查询
    getVehicleQueryPage()
    // 获取线路分页查询
    getLineQueryPage()
    // 获取电子围栏分页查询
    getFenceQueryPage()
})

/**
 * 获取车企详情
 */
const getManufacturerDetail = () => {
    backManufacturerDetail({id:state.manufacturerId}).then(res => {
        // console.log(res)
        if(res && res.status === "000_0000_0000"){
            state.manufacturerDetail = res.result
        }
    })
}

/**
 * 获取车辆分页查询
 */
const getVehicleQueryPage = () => {
    backVehicleQueryPage({
        manufacturerId: state.manufacturerId,
        pageNum: vehiclePagination.value.current,
        pageSize: vehiclePagination.value.pageSize
    }).then(res => {
        if(res && res.status === "000_0000_0000"){
            state.vehicleData = res.result.list || []
            console.log(state.vehicleData, 'state.vehicleData')
            vehiclePagination.value.total = Number(res.result.total)
        }
    })
}

/**
 * 获取线路分页查询
 */
const getLineQueryPage = () => {
    backLineQueryPage({
        manufacturerId: state.manufacturerId,
        pageNum: routePagination.value.current,
        pageSize: routePagination.value.pageSize
    }).then(res => {
        if(res && res.status === "000_0000_0000"){
            state.routeData = res.result.list || []
            routePagination.value.total = Number(res.result.total)
        }
    })
}

/**
 * 获取电子围栏分页查询
 */
const getFenceQueryPage = () => {
    backFenceQueryPage({manufacturerId: state.manufacturerId}).then(res => {
        if(res && res.status === "000_0000_0000"){
            state.fenceData = res.result.list || []
            // fencePagination.value.total = Number(res.result.total)
        }
    })
}

/**
 * 获取车辆详情
 */
const getVehicleDetail = () => {
    backVehicleDetail({}).then(res => {
        console.log(res)
    })
}

/**
 * 接入车辆
 */
const getVehicleOptCount = () => {
    backVehicleOptCount({}).then(res => {
        console.log(res)
    })
}

onUnmounted(() => {
    if (mapInstance) {
        mapInstance.destroy()
    }
})
</script>

<style scoped lang="less">
.company-desktop {
    // padding: 24px;
    // background: #f5f5f5;
    height: 100%;
    display: flex;
    flex-direction: column;
}

.top-cards {
    display: flex;
    gap: 24px;
    margin-bottom: 24px;
}

.overview-card,
.company-card {
    background: #fff;
    border-radius: 8px;
    padding: 24px;
    box-shadow: 0 2px 8px rgba(0, 0, 0, 0.1);
}

.overview-card {
    flex: 2;
}

.company-card {
    flex: 1;
    padding:20px 24px 10px 24px;
    .card-title{
         border-bottom: 1px solid #f0f0f0;
         }
}

.card-title {
    font-size: 18px;
    font-weight: 600;
    color: #333;
    // margin-bottom: 20px;
    padding-bottom: 12px;
    // border-bottom: 1px solid #f0f0f0;
}

.overview-grid {
    height: calc(100% - 40px);
    display: grid;

    grid-template-columns: repeat(4, 1fr);
    gap: 16px;
    // justify-items: center;
    align-items: center;
}

.overview-item {
    text-align: center;
    padding: 20px;
    border-radius: 8px;
    color: #fff;
    
    &.green {
        background: linear-gradient(135deg, #52c41a, #73d13d);
    }
    
    &.red {
        background: linear-gradient(135deg, #ff4d4f, #ff7875);
    }
    
    &.teal {
        background: linear-gradient(135deg, #13c2c2, #36cfc9);
    }
    
    &.blue {
        background: linear-gradient(135deg, #1890ff, #40a9ff);
    }
    
    .number {
        font-size: 28px;
        font-weight: bold;
        margin-bottom: 8px;
    }
    
    .label {
        font-size: 14px;
        opacity: 0.9;
    }
}

.company-info {
    .info-item {
        display: flex;
        justify-content: space-between;
        align-items: center;
        padding: 8px 0;
        border-bottom: 1px solid #f5f5f5;
        
        &:last-child {
            border-bottom: none;
        }
        
        .label {
            color: #666;
            font-weight: 500;
        }
        
        .value {
            color: #333;
            
            &.status-uploaded {
                color: #52c41a;
                font-weight: 500;
            }
        }
    }
}

.tab-content {
    background: #fff;
    border-radius: 8px;
    box-shadow: 0 2px 8px rgba(0, 0, 0, 0.1);
    overflow: hidden;
    flex: 1;
    padding: 0 20px;
}

.main-tabs {

    :deep(.ant-tabs-nav) {
        margin: 0;
        padding: 0 24px;
        background: #fafafa;
        border-bottom: 1px solid #f0f0f0;
    }
    
    :deep(.ant-tabs-content-holder) {
        padding: 24px;
    }
}

.vehicle-list-content,
.routes-content {
    min-height: 400px;
}

.areas-content {
    .map-container {
        border: 1px solid #d9d9d9;
        border-radius: 6px;
        overflow: hidden;
        
        .map-content {
            height: 500px;
            width: 100%;
        }
    }
}

// 响应式设计
@media (max-width: 1200px) {
    .top-cards {
        flex-direction: column;
    }
    
    .overview-grid {
        grid-template-columns: repeat(2, 1fr);
    }
}

@media (max-width: 768px) {
    .company-desktop {
        padding: 16px;
    }
    
    .overview-grid {
        grid-template-columns: 1fr;
    }
}
</style>